package HighConcurrency.Nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Channel {
    public static void main(String[] args) throws IOException
    {
        SocketChannel sc=SocketChannel.open();//打开客户端通道
        sc.configureBlocking(false);//设置为非阻塞，非阻塞无论是否链接，都不会等待继续运行
        //sc.connect(new InetSocketAddress("localhost",8090));//发起连接
        //System.out.println(111);


//        while (!sc.isConnected())//如果没有连接
//        {
//            sc.finishConnect();//试图重新链接，且计数，如果多次无法链接，抛出异常。
//        }
//        //构建缓存区
//        ByteBuffer buffer=ByteBuffer.wrap("hello".getBytes());
//        //写入
//        sc.write(buffer);
//        //关流
//        sc.close();


        sc.configureBlocking(true);
        sc.connect(new InetSocketAddress("localhost",8090));
        sc.write(ByteBuffer.wrap("hello".getBytes()));//写入
        ByteBuffer bb=ByteBuffer.allocate(1024);
        sc.read(bb);
        byte[] a=bb.array();
        System.out.println(new String(a,0,bb.position()));
        sc.close();

    }
}
